<?php

namespace app\adminapi\logic\admin;

use adminmatrix\admin\annotation\Inject;
use adminmatrix\admin\logic\BaseLogic;
use app\adminapi\logic\system\PermissionLogic;
use app\adminapi\model\Admin\Admin;
use app\adminapi\service\AdminTokenService;
use app\adminapi\validate\admin\AdminValidate;
use app\Request;
use hg\apidoc\annotation as Apidoc;
use think\exception\HttpException;

class AdminLogic extends BaseLogic
{
    #[Inject]
    protected Admin $model;
    #[Inject]
    protected AdminTokenService $service;


    public function update(Request $request) : bool
    {
        try {
            $params = $request->put();
            $result = $this->model->where('id' , $params['id'] ) -> findOrEmpty();
            if ($result->isEmpty()) throw new HttpException(200 , '未知的管理员信息');
            # 先删除旧的信息
            if ($result->role->count() > 0 ) $result->role->delete();

            $role = [];
            foreach ($params['role'] as $roleId)
            {
                $role[] = ["role_id" => $roleId];
            }
//            dump($role);
            $result->role()->saveAll($role);

            $result->save($params);
            return true;
        } catch (HttpException $e)
        {
            throw new HttpException($e->getCode() , $e->getMessage());
        }
    }



    public function login(Request $request) : array
    {
        $admin = $this->get($request , ["username" => $request->post('username')]);
        if ($admin->isEmpty())
            throw new HttpException(200 , '管理员不存在');
        if($admin->password != md5($request->post('password') . $admin->salt))
            throw new HttpException(200 , '管理员账号或密码错误');

        $admin->last_login_time = time();
        $admin->last_login_ip   =   $request->ip();
        $admin->save();
       return $this->service->setToken($admin->id);
    }

    public function get(Request $request, ?array $where = []): mixed
    {
        return parent::get($request , $where);
    }

    public function mySelf($id) : array
    {
        $admin = $this->model->withJoin(['session'])
            ->with(['role'])
            ->withAttr('role' , function($query){
                return $query->column('role_id');
            })
            ->find($id);
        $admin =  [
            'id'        =>  $admin->id,
            'username'  =>  $admin->username,
            'nickname'  =>  $admin->nickname,
            'root'      =>  $admin->root,
            'token'     =>  $admin->session->token,
            'expire_time'   =>  $admin->session->expire_time,
            'role'      =>  $admin->role,
        ];



        return  [
            'userInfo'     =>  $admin,
            'routes'    =>  (new PermissionLogic ) -> getPermis($admin['id']),
            'permissions'   => $admin['root'] == 1 ? ["*"] : (new PermissionLogic ) -> getAuthByAdminId($admin['id'])
        ];
    }


    public function save(Request $request ) : bool
    {
        $validate = new AdminValidate();
        $params = $validate->post()->goCheck('save');
        $salt  = uniqid('matrix_');
        $params['password'] =  md5('admin' . $salt);
        $params['salt'] =   $salt;
        return  $this->model->save($params);
    }


    public function logout(Request $request) : bool
    {
        return  AdminTokenService::expireToken($request->header('token'));
    }
}